<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>添加设备</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
        }

        body {
            min-height: 100vh;
            background: linear-gradient(135deg, #f8faf6 0%, #e6f7eb 100%);
            color: #334155;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            background: linear-gradient(135deg, #4caf50 0%, #81c784 100%);
            color: white;
            padding: 20px;
            border-radius: 12px;
            margin-bottom: 20px;
            box-shadow: 0 4px 20px rgba(76, 175, 80, 0.2);
        }

        .header h1 {
            font-size: 24px;
            font-weight: 600;
            display: flex;
            align-items: center;
        }

        .header h1::before {
            content: "➕";
            margin-right: 10px;
            font-size: 28px;
        }

        .card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
            padding: 20px;
            margin-bottom: 20px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            font-size: 14px;
            margin-bottom: 8px;
            color: #2e7d32;
            font-weight: 500;
        }

        .form-control {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #c8e6c9;
            border-radius: 6px;
            font-size: 14px;
            transition: all 0.3s ease;
            background-color: white;
            outline: none;
        }

        .form-control:focus {
            border-color: #4caf50;
            box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
        }

        .icon-preview {
            width: 60px;
            height: 60px;
            border: 1px solid #c8e6c9;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-top: 10px;
            background-color: #f1f8e9;
        }

        .icon-preview img {
            max-width: 50px;
            max-height: 50px;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 5px;
        }

        .btn-primary {
            background-color: #4caf50;
            color: white;
        }

        .btn-primary:hover {
            background-color: #388e3c;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(56, 142, 60, 0.3);
        }

        .btn-secondary {
            background-color: #81c784;
            color: white;
            margin-left: 10px;
        }

        .btn-secondary:hover {
            background-color: #66bb6a;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(102, 187, 106, 0.3);
        }

        .form-actions {
            display: flex;
            justify-content: center;
            margin-top: 30px;
        }

        .notification {
            padding: 10px 15px;
            border-radius: 6px;
            margin-bottom: 20px;
            display: none;
        }

        .notification-success {
            background-color: #e8f5e9;
            color: #2e7d32;
            border: 1px solid #c8e6c9;
        }

        .notification-error {
            background-color: #ffebee;
            color: #c62828;
            border: 1px solid #ffcdd2;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>添加设备</h1>
    </div>

    <div class="notification" id="notification"></div>

    <div class="card">
        <form id="deviceForm" enctype="multipart/form-data">
            <div class="form-group">
                <label for="devName">设备名称</label>
                <input type="text" id="devName" name="devName" class="form-control" required>
            </div>

            <div class="form-group">
                <label for="devType">设备类型</label>
                <select id="devType" name="devType" class="form-control" required>
                    <option value="">请选择设备类型</option>
                    <option value="灌溉设备">灌溉设备</option>
                    <option value="监测设备">监测设备</option>
                    <option value="气象设备">气象设备</option>
                </select>
            </div>

            <div class="form-group">
                <label for="lon">经度</label>
                <input type="text" id="lon" name="lon" class="form-control" required>
            </div>

            <div class="form-group">
                <label for="lat">纬度</label>
                <input type="text" id="lat" name="lat" class="form-control" required>
            </div>
            
            <div class="form-group">
                <label>地图选点</label>
                <div id="mapContainer" style="width: 100%; height: 400px; border: 1px solid #c8e6c9; border-radius: 6px;"></div>
                <p style="margin-top: 5px; font-size: 12px; color: #666;">点击地图选择设备位置</p>
            </div>

            <div class="form-group">
                <label for="isValid">状态</label>
                <select id="isValid" name="isValid" class="form-control" required>
                    <option value="1">启用</option>
                    <option value="0">禁用</option>
                </select>
            </div>

            <div class="form-group">
                <label for="iconName">图标名称</label>
                <select id="iconName" name="iconName" class="form-control" required>
                    <option value="">请选择图标</option>
                    <option value="irrigation.png">灌溉设备图标</option>
                    <option value="soil_sensor.png">土壤监测仪图标</option>
                    <option value="weather_station.png">气象站图标</option>
                    <option value="pest_monitor.png">病虫害监测仪图标</option>
                </select>
                <div class="icon-preview" id="iconPreview">
                    <span>图标预览</span>
                </div>
            </div>

            <div class="form-actions">
                <button type="submit" class="btn btn-primary">
                    <span>💾</span> 保存设备
                </button>
                <button type="button" class="btn btn-secondary" onclick="goBack()">
                    <span>↩️</span> 返回列表
                </button>
            </div>
        </form>
    </div>
</div>

<script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=VnGlMeazeUx3wuGWmk88DgsXbwnRJhGK"></script>
<script>
    // 图标映射
    const iconMap = {
        'irrigation.png': '💧',
        'soil_sensor.png': '🌡️',
        'weather_station.png': '🌤️',
        'pest_monitor.png': '🐛'
    };
    
    // 百度地图相关变量
    let map;
    let marker;

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 输出图标数据到控制台
        console.log('可用图标列表:', iconMap);
        
        // 确保百度地图API完全加载后再初始化地图
        if (typeof BMap !== "undefined") {
            // 使用setTimeout确保DOM已完全渲染
            setTimeout(initBaiduMap, 100);
        } else {
            // 如果BMap还未加载，则监听百度地图API加载完成事件
            window.onBMapReady = function() {
                setTimeout(initBaiduMap, 100);
            };
            console.error("百度地图API正在加载中...");
        }
        
        // 监听图标下拉框变化
        const iconSelect = document.getElementById('iconName');
        const iconPreview = document.getElementById('iconPreview');
        
        // 初始化百度地图函数
        function initBaiduMap() {
            // 创建地图实例
            map = new BMap.Map("mapContainer");
            
            // 设置地图中心点和缩放级别（默认北京）
            const point = new BMap.Point(116.404, 39.915);
            map.centerAndZoom(point, 15);
            
            // 添加地图控件
            map.addControl(new BMap.NavigationControl());
            map.addControl(new BMap.ScaleControl());
            
            // 启用滚轮缩放
            map.enableScrollWheelZoom(true);
            
            // 添加点击事件
            map.addEventListener("click", function(e) {
                const point = e.point;
                
                // 移除之前的标记
                if (marker) {
                    map.removeOverlay(marker);
                }
                
                // 获取当前选择的图标
                const selectedIcon = iconSelect.value;
                let iconToUse;

                // 如果有选择图标，使用自定义图标
                if (selectedIcon && iconMap[selectedIcon]) {
                    iconToUse = new BMap.Icon(
                        `${window.location.origin}/pointmap/img/${selectedIcon}`,
                        new BMap.Size(32, 32),
                        {
                            offset: new BMap.Size(16, 16), // 指定定位位置
                            imageOffset: new BMap.Size(0, 0)  // 设置图片偏移
                        }
                    );
                } else {
                    // 否则使用默认图标
                    iconToUse = new BMap.Icon("https://api.map.baidu.com/images/marker_red_sprite.png", new BMap.Size(22, 25));
                }

                // 添加新标记
                marker = new BMap.Marker(point, {icon: iconToUse});
                map.addOverlay(marker);
                
                // 更新经纬度输入框
                document.getElementById('lon').value = point.lng.toFixed(6);
                document.getElementById('lat').value = point.lat.toFixed(6);
                
                console.log('已选择位置:', '经度:', point.lng, '纬度:', point.lat);
            });
            
            // 如果已有经纬度，则添加标记
            const lon = document.getElementById('lon').value;
            const lat = document.getElementById('lat').value;
            if (lon && lat) {
                const existingPoint = new BMap.Point(parseFloat(lon), parseFloat(lat));
                
                // 获取当前选择的图标
                const selectedIcon = iconSelect.value;
                let iconToUse;

                // 如果有选择图标，使用自定义图标
                if (selectedIcon && iconMap[selectedIcon]) {
                    iconToUse = new BMap.Icon(
                        `${window.location.origin}/img/${selectedIcon}`,
                        new BMap.Size(32, 32),
                        {
                            offset: new BMap.Size(16, 16), // 指定定位位置
                            imageOffset: new BMap.Size(0, 0)  // 设置图片偏移
                        }
                    );
                } else {
                    // 否则使用默认图标
                    iconToUse = new BMap.Icon("https://api.map.baidu.com/images/marker_red_sprite.png", new BMap.Size(22, 25));
                }
                
                marker = new BMap.Marker(existingPoint, {icon: iconToUse});
                map.addOverlay(marker);
                map.centerAndZoom(existingPoint, 15);
            }
        }

        iconSelect.addEventListener('change', function() {
            updateIconPreview();
        });
        
        // 更新图标预览函数
        function updateIconPreview() {
            const selectedIcon = iconSelect.value;
            if (selectedIcon && iconMap[selectedIcon]) {
                iconPreview.innerHTML = `<span style="font-size: 30px;">${iconMap[selectedIcon]}</span>`;
                console.log('已选择图标:', selectedIcon, '对应的表情符号:', iconMap[selectedIcon]);
            } else {
                iconPreview.innerHTML = '<span>图标预览</span>';
            }
        }
        
        // 初始化图标预览
        updateIconPreview();

        // 表单提交处理
        const deviceForm = document.getElementById('deviceForm');
        deviceForm.addEventListener('submit', function(e) {
            e.preventDefault();

            // 创建FormData对象用于文件上传
            const formData = new FormData();
            formData.append('devName', document.getElementById('devName').value);
            formData.append('devType', document.getElementById('devType').value);
            formData.append('lon', document.getElementById('lon').value);
            formData.append('lat', document.getElementById('lat').value);
            formData.append('isValid', document.getElementById('isValid').value);
            formData.append('iconName', document.getElementById('iconName').value);

            // 设置请求头，表明这是AJAX请求
            const headers = new Headers();
            headers.append('X-Requested-With', 'XMLHttpRequest');

            // 发送AJAX请求
            fetch('deviceServlet?actionType=devAdd&format=json', {
                method: 'POST',
                body: formData,
                headers: headers
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应异常');
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    showNotification('设备添加成功', 'success');
                    setTimeout(() => {
                        window.location.href = 'deviceManagement.jsp';
                    }, 1500);
                } else {
                    showNotification('设备添加失败: ' + data.message, 'error');
                }
            })
            .catch(error => {
                console.error('请求失败:', error);
                showNotification('设备添加失败，请稍后再试', 'error');
            });
        });
    });

    // 显示通知
    function showNotification(message, type) {
        const notification = document.getElementById('notification');
        notification.textContent = message;
        notification.className = 'notification notification-' + type;
        notification.style.display = 'block';

        // 3秒后自动隐藏
        setTimeout(() => {
            notification.style.display = 'none';
        }, 3000);
    }

    // 返回设备列表
    function goBack() {
        window.location.href = 'deviceManagement.jsp';
    }
</script>
</body>
</html>